import { reactive, ToRefs, toRefs } from "vue";
import { Router, useRouter } from "vue-router";
import ComponentController from '@/common/controller';
import {setToken, SetTokenParams} from '@/utils/token';
import LoginApi from "@/api/user"
import { Store } from "vuex";

/**
 * 登录页面控制器
 */
class LoginController extends ComponentController{
    private router:Router=useRouter();
    state: { form: { username: string; password: string; remember: boolean; }; formRules: any; loading: boolean; };
    store: Store<any>;
	constructor(store:Store<any>){
        super()
        this.state=reactive({
			form:{
				username:'',
				password:'',
				remember:false,
			},
			formRules:{
				username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
				password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
			},
			loading:false
		})
		this.store=store
    }
    /**获取state */
    getState(){
        return {
			...toRefs(this.state),
		}
    }

    /**获取methods */
    getMethods(){
        return {
			setRemember:this.setRemember.bind(this),
			onSubmit:this.onSubmit.bind(this)
		}
    }

    private setRemember(e:any){
        this.state.form.remember=e.target?.checked
    }

    private onSubmit(e:any){
        this.state.loading=true
        let phone=this.state.form.username
        let password=this.state.form.password
        LoginApi.login({phone,password}).then(res => {
            var data = res.data
			this.store.commit('app/setUserInfo',data.user)

            setToken({
                token:data.token,
                remember:this.state.form.remember,
            })

        }).finally(()=>{
			setTimeout(() => {
                this.state.loading=false
                this.router.replace('/')
            }, 500);
		})
    }
}

export default LoginController
